﻿using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.Appicant.Command.Routing;
using B.S.DataBase.MyRead.API.DTOs;
using MediatR;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler.Routing
{
    public class GetRouterCommandHandler : IRequestHandler<GetRouterCommand, APIResult<List<MenuRouterDTO>>>
    {
        private readonly IBaseRepository<Menu> _menuRep;

        public GetRouterCommandHandler(IBaseRepository<Menu> menuRep)
        {
            _menuRep = menuRep;
        }

        public async Task<APIResult<List<MenuRouterDTO>>> Handle(GetRouterCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 使用异步方法获取数据，避免阻塞
                var menus = await _menuRep.GetAll(); // 假设您的仓库有异步方法

                var result = new APIResult<List<MenuRouterDTO>>
                {
                    Code = APIEnum.查询成功,
                    Msg = APIEnum.查询成功.ToString(),
                    data = BuildMenuTree(menus, 0)
                };

                return await Task.FromResult(result);
            }
            catch (Exception ex)
            {
                // 添加异常处理
                return new APIResult<List<MenuRouterDTO>>
                {
                    Code = APIEnum.查询失败,
                    Msg = $"获取菜单失败：{ex.Message}"
                };
            }
        }

        private List<MenuRouterDTO> BuildMenuTree(IEnumerable<Menu> menus, int pid)
        {
            return menus
                .Where(m => m.PId == pid)
                .OrderBy(m => m.MenuId) // 添加排序保证树结构顺序
                .Select(m => new MenuRouterDTO
                {
                    MenuId = m.MenuId,
                    MenuName = m.MenuName,
                    Url = m.Url,
                    PId = m.PId,
                    Children = BuildMenuTree(menus, m.MenuId)
                }).ToList();
        }
    }
}
